<!--
*@Author: zt
*@Description: 备勤管理
*@Date: 2024-08-20
-->
<template>
  <a-layout class="f-h-100 s-b-white">
    <template v-if="!showCalendar">
      <a-layout-sider
        theme="light"
        width="300"
        style="padding: 10px; border-right: 1px solid #d9d9d9">
        <a-calendar
          v-model:value="calenderValue"
          :fullscreen="false"
          @change="
            () => {
              userData();
              getSearch(1);
            }
          ">
          <template #headerRender="{ value: current, type, onChange, onTypeChange }">
            <a-row
              jusityfy="space-between"
              align="middle"
              class="f-w-100 f-padding-tb10">
              <a-col :span="12">
                <a-date-picker
                  v-model:value="calenderValue"
                  format="YYYY年MM月" />
              </a-col>
              <a-col
                :span="12"
                align="end">
                <a-space>
                  <LeftOutlined
                    class="f-cursor"
                    style="color: #aaa"
                    @click="jumpDate('up')" />
                  <RightOutlined
                    class="f-cursor"
                    style="color: #aaa"
                    @click="jumpDate('next')" />
                </a-space>
              </a-col>
            </a-row>
          </template>
        </a-calendar>
      </a-layout-sider>
      <a-layout-content>
        <a-layout class="f-h-100 s-bg-white">
          <u-search-header style="padding: 0 16px">
            <a-row
              class="f-font-family"
              style="font-size: var(--font-size-level-2); color: #1890ff">
              <b>当日备勤总人数 {{ sumData }} 人</b>
            </a-row>
            <u-form
              :model="searchF.model"
              :gutter="16"
              :elements="searchEl"
              class="f-w-auto"
              :isSearch="true"
              @formChange="getSearch(1)">
              <a-col>
                <u-icon-button @click="getSearch(1)">查询</u-icon-button>
              </a-col>
              <a-col flex="1">
                <a-row justify="end">
                  <a-space>
                    <u-icon-button
                      class="f-fr"
                      itype="add"
                      @click="showEdit = true">
                      添加备勤
                    </u-icon-button>
                    <u-icon-button
                      class="f-fr"
                      itype="close"
                      @click="delBtn()">
                      取消备勤
                    </u-icon-button>
                    <u-icon-button @click="showCalendar = !showCalendar">视图切换</u-icon-button>
                  </a-space>
                </a-row>
              </a-col>
            </u-form>
          </u-search-header>
          <u-table-content class="f-padding-rl20">
            <u-table
              :columns="columns"
              :data="tabData"
              :scroll="{ y: useTableScroll() }"
              v-model:pagination="pagenation"
              @onDblclick="onDblclick"
              @onSelect="({ selectedRows }) => tabSelData.splice(0, tabSelData.length, ...selectedRows)"
              @change="getSearch()">
            </u-table>
          </u-table-content>
        </a-layout>
      </a-layout-content>
    </template>
    <template v-if="showCalendar">
      <u-table-header>
        <a-row justify="end">
          <u-icon-button @click="showCalendar = !showCalendar">视图切换</u-icon-button>
        </a-row>
      </u-table-header>
      <u-table-content style="margin-top: -60px">
        <Calendar
          :showExtraTool="false"
          v-model:date="clickDateValue"
          :data="calendarData"
          @search="getCalendarData"
          @select="
            (value) => {
              clickDateValue = value;
              getCalendarData();
            }
          "
          @item-click="
            (data) => {
              userListRow(data.standbyDate);
            }
          "></Calendar>
      </u-table-content>
    </template>
  </a-layout>

  <!-- 编辑弹窗 -->
  <Edit
    v-model:open="showEdit"
    :keyid="keyid"
    wrap-class-name="full-modal"
    :dbDisabled="dbDisabled"
    :calenderValue="calenderValue"
    @success="
      (date) => {
        dbDisabled = false;
        showEdit = false;
        if (date) {
          calenderValue = dayjs(date);
        }
        getSearch(1);
      }
    "
    :title="dialogTitle"
    @close="() => {
      getSearch(1); 
      showEdit = false; 
      dbDisabled = false;
      keyid = ''
    }" />

  <userRow
    v-model:open="showUserRow"
    width="80%"
    :data="useListData"
    title="当日备勤人员" />
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, onUnmounted } from "vue";
import { _IFormEl } from "@/components/common/form/interface";
import { FormItemProps, TableColumnProps } from "ant-design-vue";
import { messageC } from "@/util/common";
import { storeToRefs } from "pinia";
import { useBaseStore } from "@/store";
import { alertC } from "@/util/common";
import { useTableScroll } from "@/hooks/useTable";
import dayjs, { Dayjs } from "dayjs";
import Edit from "./Edit.vue";
import Calendar from "@/views/oa/assist/myCalender/Calender.vue";
import userRow from "./row.vue";

import * as depUserApi from "@/service/personnel/work/index";
import * as beDutyApi from "@/service/administration/beDuty/index";

let keyid = ref("");
let showUserRow = ref(false);
let useListData = ref([]);
const { deptData, DUTY_TYPE } = storeToRefs(useBaseStore());
let sumData = ref(0);
const calenderValue = ref<Dayjs>(dayjs());
const tabSelData = ref([]);
const dbDisabled = ref(false);
const showCalendar = ref<boolean>(false);

let pagenation = reactive({
  current: 1,
  pageSize: 50,
  total: 0,
  showTotal: (total) => `共 ${total} 条`,
});
const searchF = reactive({
  model: {
    backuptype: 1,
  },
});
const formItemProps: FormItemProps = {
  labelCol: { span: 5 },
  wrapperCol: { span: 19 },
};
const searchEl: Array<_IFormEl> = [
  {
    label: "模糊查询",
    key: "keywords",
    element: "input",
    col: { span: 6 },
    formItemProps: formItemProps,
    componentProps: { placeholder: "请输入姓名，电话" },
  },
  {
    label: "部门",
    key: "fkdeptid",
    element: "select",
    col: { span: 4 },
    formItemProps: formItemProps,
    componentProps: {
      options: deptData.value,
    },
  },
];

// 列表
let tabData = ref([]);
let columns: Array<TableColumnProps> = reactive([
  {
    dataIndex: "index",
    title: "序号",
    width: 60,
    align: "center",
    customRender: ({ text, record, index }) => {
      return index + 1;
    },
  },
  { dataIndex: "fkdeptname", title: "部门", width: 340, align: "center" },
  { dataIndex: "fkusername", title: "姓名", width: 150, align: "center" },
  { dataIndex: "tel", title: "联系电话", width: 160, align: "center" },
  { dataIndex: "duty", title: "职务", width: 120, align: "center" },
  { dataIndex: "dutyStatus", title: "在岗情况", width: 120, align: "center" },
  { dataIndex: "reason", title: "备注", width: 130 },
]);
const jumpDate = (type: string) => {
  calenderValue.value = type == "up" ? dayjs(calenderValue.value).subtract(1, "day") : dayjs(calenderValue.value).add(1, "day");
};

// 查询数据
const getSearch = async (index) => {
  if (index == 1) {
    pagenation.current = 1;
  }
  // 转换格式为时间搓
  searchF.model["dateTime"] = dayjs(calenderValue.value).format("YYYY-MM-DD");

  let tform = JSON.parse(JSON.stringify(searchF));
  const res = await beDutyApi.page({
    ...pagenation,
    size: pagenation.pageSize,
    ...tform,
  });
  if (res.code == 0) {
    tabData.value = res.data.records;
    pagenation.total = res.data.total;
  }
  DUTY_TYPE.value.map((e) => {
    tabData.value.map((index) => {
      if (index.duties == e.code || index.duties == e.id) {
        index["dutiesName"] = e.name;
      }
    });
  });

  await userData();
  await getCalendarData();
};

//删除
const delBtn = async () => {
  if (tabSelData.value.length == 0) {
    return alertC("请先选择要删除的数据！");
  }
  alertC("确定删除选中的数据?", "confirm")
    .then(async () => {
      let ids = [];
      tabSelData.value.map((item) => ids.push(item.keyid));
      const res = await beDutyApi.del({ ids: ids.join(",") });
      if (res.code == 0) {
        messageC(res.msg, "success");
        getSearch(1);
      } else {
        alertC(res.msg, "warning");
      }
    })
    .catch({});
};

// 编辑
let dialogTitle = ref<string>("添加备勤");
let showEdit = ref<boolean>(false);

const onDblclick = (record) => {
  keyid.value = record["keyid"];
  dbDisabled.value = true;
  showEdit.value = true;
};
const userData = async () => {
  const res = await depUserApi.deptUser({
    datetime: dayjs(dayjs(calenderValue.value).valueOf()).format("YYYY-MM-DD"),
  });
  if (res.code == 0 && res.data) {
    sumData.value = res.data.standNumber ?? 0;
  }
};

// 日历数据
const clickDateValue = ref<Dayjs>(dayjs().format("YYYY-MM-DD"));
const calendarData = ref<any[]>([]);
const getCalendarData = async () => {
  try {
    const res = await beDutyApi.dutyUserPage({
      datetime: clickDateValue.value,
      backuptype: 1,
    });
    if (res.code == 0) {
      let tData = res.data || [];
      tData.forEach((item) => {
        item.scheduledate = dayjs(item.standbyDate).format("YYYY-MM-DD HH:mm:ss");
        item.theme = item.fkusername;
      });

      calendarData.value = tData;
    }
  } catch (error) {}
};

// 查询视图数据
const userListRow = async (date) => {
  try {
    const res = await beDutyApi.dutyUserPage({
      datetime: clickDateValue.value,
      backuptype: 1,
    });
    if (res.code == 0) {
      let tData = res.data || [];
      tData.forEach((item) => {
        item.scheduledate = dayjs(item.standbyDate).format("YYYY-MM-DD HH:mm:ss"); 
        item.theme = item.fkusername;
      });
      useListData.value = [];
      tData.forEach((item) => {
        if (item.scheduledate == date) {
          useListData.value.push(item);
        }
      });
      showUserRow.value = true;
    }
  } catch (error) {}
};

onMounted(async () => {
  await userData();
  await getSearch(1);
  getCalendarData();
});

onUnmounted(() => {
  showCalendar.value = false;
});
</script>
<style lang="scss" scoped>
:deep(.u-calender-cell-work) {
  .u-calend-work-area {
    &:nth-child(4) {
      height: max-content;
      &::after {
        position: absolute;
        top: 0;
        left: -2px;
        width: 100%;
        background-color: inherit;
        content: '...';
        padding: inherit
      }
      span {
        display: none;
      }
    }
    &:nth-child(n+5) {
      display: none;
    }
  }
}
</style>
